package gui;

import Auxiliar.Constantes;
import buscador.Indexador;
import buscador.Searcher;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author proyectosbeta
 */
public class Principal extends javax.swing.JFrame {

    /**
     * Creates new form Principal
     */
    public Principal() {
        // Se elije el tema por defecto de la aplicación.
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch(Exception e){
            // Look and Feel predeterminado de Java.
            UIManager.getCrossPlatformLookAndFeelClassName();
        }
        initComponents();
        
        // No se puede editar donde se muestra el contenido (html).
        jEditorPaneContenido.setEditable(false);
        
        // Pantalla Completa.
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonIndexar = new javax.swing.JButton();
        jTextFieldBuscador = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jListaResultado = new javax.swing.JList();
        jButtonBuscar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jEditorPaneContenido = new javax.swing.JEditorPane();
        jMenuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButtonIndexar.setText("Indexar");
        jButtonIndexar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonIndexarActionPerformed(evt);
            }
        });

        jTextFieldBuscador.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldBuscadorActionPerformed(evt);
            }
        });

        jListaResultado.setModel(new javax.swing.AbstractListModel() {
            String[] strings = {};
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jListaResultado.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jListaResultadoMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(jListaResultado);

        jButtonBuscar.setText("Buscar");
        jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(jEditorPaneContenido);

        jMenu1.setText("Salir");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Salir");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar.add(jMenu1);

        jMenu2.setText("Ayuda");

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText("Acerca de");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        jMenuBar.add(jMenu2);

        setJMenuBar(jMenuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonIndexar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextFieldBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButtonBuscar)
                        .addGap(0, 111, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jButtonIndexar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldBuscador, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonBuscar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane2))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 434, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 19, Short.MAX_VALUE)))
                .addGap(12, 12, 12))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        String codigoHTML = "<html><body><p><b>&nbsp;&nbsp;&nbsp;&nbsp;Autor:</b> " +
            "José González von Schmeling<br><b>&nbsp;&nbsp;&nbsp;&nbsp;Mail:</b> " +
            "josego85@gmail.com<br><b>&nbsp;&nbsp;&nbsp;&nbsp;Autor:</b> " +
            "José Pino<br><b>&nbsp;&nbsp;&nbsp;&nbsp;Mail:</b> " +
            "josepino@gmail.com<br><b>&nbsp;&nbsp;&nbsp;&nbsp;Año:</b> 2012" +
            "<br><b>&nbsp;&nbsp;&nbsp;&nbsp;Buscador v.1.0</b></body></html>";
        JOptionPane.showMessageDialog(this, codigoHTML,
            "" + Constantes.INCREMENTO_CANTIDAD_DE_ESPACIO_TITULO + 
            Constantes.TITULO_PROGRAMA, JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jButtonIndexarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIndexarActionPerformed
        String mensaje = "Creando indices...";
        /*JOptionPane.showMessageDialog(this, mensaje,
            "" + Constantes.INCREMENTO_CANTIDAD_DE_ESPACIO_TITULO + 
            Constantes.TITULO_PROGRAMA, JOptionPane.PLAIN_MESSAGE);
        */
        // Se indexa los documentos.
        indexador = new Indexador();
        indexador.crearIndice(true);
        
        mensaje = "Se indexó " + indexador.getCantidadDeDocumentosIndexados() + " documentos";
        JOptionPane.showMessageDialog(this, mensaje,
            "" + Constantes.INCREMENTO_CANTIDAD_DE_ESPACIO_TITULO + 
            Constantes.TITULO_PROGRAMA, JOptionPane.PLAIN_MESSAGE);
    }//GEN-LAST:event_jButtonIndexarActionPerformed

    private void jTextFieldBuscadorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldBuscadorActionPerformed
        if(verificarExistenciaIndex()){
            buscarContenido();
        }else{
             String mensaje = "Se se puede buscar porque no se indexó todavía.\nPresione"
                 + " el boton Indexar.";
             JOptionPane.showMessageDialog(this, mensaje,
                 "" + Constantes.INCREMENTO_CANTIDAD_DE_ESPACIO_TITULO + 
                 Constantes.TITULO_PROGRAMA, JOptionPane.PLAIN_MESSAGE);
        } // Fin del else.
    }//GEN-LAST:event_jTextFieldBuscadorActionPerformed

    private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed
        if(verificarExistenciaIndex()){
            buscarContenido();
        }else{
             String mensaje = "Se se puede buscar porque no se indexó todavía.\nPresione"
                 + " el boton Indexar.";
             JOptionPane.showMessageDialog(this, mensaje,
                 "" + Constantes.INCREMENTO_CANTIDAD_DE_ESPACIO_TITULO + 
                 Constantes.TITULO_PROGRAMA, JOptionPane.PLAIN_MESSAGE);
        } // Fin del else.
        //mostrarContenido("");
    }//GEN-LAST:event_jButtonBuscarActionPerformed

    private void jListaResultadoMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jListaResultadoMousePressed
        JList list = (JList)evt.getSource();
        
        if (evt.getClickCount() == 2) {
            mostrarContenido((String)list.getSelectedValue());
        }
    }//GEN-LAST:event_jListaResultadoMousePressed

    // Metodos varios
    public void buscarContenido(){
        // Se busca en el index.
        seacher = new Searcher();
        
        // Variables
        List<String> listaResultado = new ArrayList<String>();
        DefaultListModel modelo = new DefaultListModel();
           
        if(!jTextFieldBuscador.getText().equals("")){
            listaResultado = seacher.searchIndex(jTextFieldBuscador.getText());
        
            Iterator iterador = listaResultado.iterator();

            while(iterador.hasNext()){
                String value = (String)iterador.next();
                modelo.addElement(value);
            }      
            jListaResultado.setModel(modelo);
        }else{
             modelo = (DefaultListModel) jListaResultado.getModel();
            
             // Eliminar todos los elementos de la lista jListaResultado.
             modelo.removeAllElements();   
        }
    } // Fin del metodo publico buscarContenido.
    
    
    // Muestra el contenido (html).
    public void mostrarContenido(String rutaDocumento) {
        
        try{
            File paginaHTML = new File(rutaDocumento);
            String urlDocumento = "file://localhost/" + paginaHTML.getAbsolutePath();  
                
            jEditorPaneContenido.setContentType("text/html"); 
            jEditorPaneContenido.setPage(new URL(urlDocumento));
        }catch(Exception e){
            e.printStackTrace();
        }
    } // Fin del metodo publico mostrarContenido.
    
    // Verifica si se creo el index.
    public boolean verificarExistenciaIndex() {
        
        try{
            File archivoIndex = new File(Constantes.DIRECTORIO_INDEXAR + "/segments.gen");
 
            if(archivoIndex.exists()){
                return true;
            }else{
               return false; 
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return false; 
    } // Fin del metodo publico verificarExistenciaIndex.
    
    /**
     * Donde se ejecuta la Ventana Principal de la aplicacion.
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Principal().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonIndexar;
    private javax.swing.JEditorPane jEditorPaneContenido;
    private javax.swing.JList jListaResultado;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jTextFieldBuscador;
    // End of variables declaration//GEN-END:variables
    
    private Indexador indexador;
    private Searcher seacher;
} // Fin de la clase Principal.